<template>
  <div class="rightContent">
    <div class="page-header">
    </div>
    <div class="flex-col-table">
      <button type="button" @click="add">
        {{ locale.fy.新增 }}
      </button>
    </div>
    <el-table :empty-text="i18n.fy.nodata" :data="data.tableData" :style="{ height: getHeight() }" border
      v-loading="data.loading" :element-loading-text="i18n.fy.loading">


      <el-table-column prop="binData" :label="locale == 'zh' ? '公司Logo' : 'projectName'" align="center">
        <template #default="scope">



          <viewer :images="images">
            <img :src="'data:image/jpg;base64,' + scope.row.binData" alt="" height="60">
          </viewer>




        </template>
      </el-table-column>


      <el-table-column prop="description" :label="locale == 'zh' ? '公司名称' : 'projectStartTime'" align="center" />
      <el-table-column prop="domain" :label="locale == 'zh' ? '公司网址' : 'illuminance'" align="center" />
      <el-table-column prop="op" :label="locale == 'zh' ? '操作' : 'operate'" width="140" align="center">
        <template #default="scope">
          <a class="layui-btn layui-btn-xs" @click="edit(scope.row)">

            {{ locale == 'zh' ? '编辑' : 'edit' }}
          </a>
          <!-- <a class="layui-btn layui-btn-danger layui-btn-xs" @click="del(scope.row)">删除</a> -->

        </template>

      </el-table-column>

    </el-table>
    <!-- <el-pagination @size-change="onChanSize" @current-change="onChanPage" v-model:current-page="data.queryForm.page"
        v-model:page-size="data.queryForm.limit" :total="data.total" /> -->
  </div>

  <div style="display: none;padding: 20px" id="saveOr3UpdateDiv">
    <form class="layui-form1" lay-filter="dataFrm-" id="dataFrm">
      <div class="layui-form-item">
        <label class="layui-form-label">

          {{ locale == 'zh' ? '公司名称' : 'entryName' }}
          :</label>
        <div class="layui-input-block">
          <input type="text" v-model="data.form.projectName" name="rolename"
            :placeholder="locale == 'zh' ? '请输入公司名称' : 'Please enter a project name'" autocomplete="off"
            class="layui-input">
        </div>
      </div>

      <div class="layui-form-item">
        <label class="layui-form-label">

          {{ locale == 'zh' ? '公司网址' : 'Ground illumination before Renovation' }}

          :</label>
        <div class="layui-input-block">
          <input type="text" v-model="data.form.originalIlluminance"
            :placeholder="locale == 'zh' ? '请输入公司网址' : 'Please input the ground illumination before the renovation'"
            autocomplete="off" class="layui-input">
        </div>
      </div>
      <div class="layui-form-item">
        <label class="layui-form-label">

          {{ locale == 'zh' ? '公司Logo' : 'Ground illumination after renovation' }}

          :</label>
        <div class="layui-input-block">
          <el-upload ref="upload" v-model:file-list="fileList" class="upload-demo" :action="actionup" :data="dataup"
            multiple :on-preview="handlePreview" :auto-upload="false" :on-remove="handleRemove"
            :before-remove="beforeRemove" :limit="1" :on-exceed="handleExceed" :on-change="loadJsonFromFile">
            <el-button type="primary">上传公司LOGo</el-button>
            <template #tip>
              <div class="el-upload__tip">
                请上传242*70px的透明图片
              </div>
            </template>
          </el-upload>
        </div>
      </div>
      <div class="layui-form-item" style="text-align: center;width:100%;float:none;clear: both;margin-left: 0;">
        <div class="layui-input-block" style="text-align: center;width:100%;float:none;clear: both;margin-left: 0;">
          <button type="button" class="layui-btn layui-btn-normal layui-btn-sm layui-icon layui-icon-release"
            lay-filter="doSubmit" lay-ssubmit="" @click="submitUpload">
            {{ locale == 'zh' ? '提交' : 'submit' }}
          </button>
          <button type="reset" @click="login"
            class="layui-btn layui-btn-warm layui-btn-sm layui-icon layui-icon-refresh">
            {{ locale == 'zh' ? '重置' : 'resetting' }}
          </button>
        </div>
      </div>
    </form>

  </div>

  </div>
</template>
<script setup>
import { genFileId } from 'element-plus'
import { useI18n } from 'vue-i18n'
const { t, locale } = useI18n()
import Clipboard from 'clipboard';
import axios from 'axios'

const { appContext: { config: { globalProperties } } } = getCurrentInstance()
let $httpUrl = globalProperties.$httpUrl;
let $httpUrl2 = globalProperties.$httpUrl2;

let columns = reactive(
  {
    'projectName': {
      'label': '项目名称',//列名称
      'queryValue': ''
    },

  }
)
let actionup = ref('');
let description = ref('');
let dataup = ref({ domain: document.domain, description: description.value });
let userOptions = ref([]);
let comName = ref('');
//?page=1&limit=30
let data = reactive({
  queryForm: {
    page: 1,
    limit: 100
  },
  tableData: [

  ],
  total: 0,
  dialog: false,
  form: {
    "projectStartTime": "",
    "illuminance": '',
    "originalIlluminance": '',
    "investmentAmount": "",
    "latitude": "''",
    "attributes": "",
    "id": '',
    projectName: "",
    projectLightInfos: [{ amount: "", power: "", lightName: '' }]
  },
  rules: {
    name: [{ required: true, message: '请输入姓名', trigger: 'change' }],
    role: [{ required: true, message: '请选择岗位', trigger: 'change' }]
  }
})
const fileList = ref([

])

const handleRemove = (file, uploadFiles) => {
  // console.log(file, uploadFiles)
}

const handlePreview = (uploadFile) => {
  dataup.value = { domain: document.domain, description: description.value };
  // console.log(' dataup.value', dataup.value);
}


const handleExceed = (files) => {
  upload.value.clearFiles()
  const file = files[0];
  file.uid = genFileId()
  upload.value.handleStart(file)
}
let uploadFiles = ref([]);
const loadJsonFromFile = (file, fileList) => {

  uploadFiles.value = fileList
}
const beforeRemove = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(
    `Cancel the transfer of ${uploadFile.name} ?`
  ).then(
    () => true,
    () => false
  )
}
const showDisabled = (obj) => {
  let arr = oldUserList.filter((item) => {
    return obj.userid == item.userid
  })
  if (arr.length > 0) {
    return false;
  } else {
    return true;
  }
}

const reQueryForm = () => { // 重置查询表单
  data.queryForm = {
    page: 1,
    limit: 100
  }
}
let oldUserList = [];
const getuserList = (params) => { // 获取表格数据
  data.loading = true;
  axios.get($httpUrl2 + '/img/getAll', {
    "deviceFid": '',
  }).then(res => {
    data.loading = false;
    data.tableData = res.data.data;
    // console.log("data.tableData", data.tableData);
  })
  // data.loading = false;
}


const currentChange = (page) => {
  // 
  pageData.queryForm.page = page
  getList({})
}

const sizeChange = (size) => {
  data.queryForm.page = size
  getList({})
}
const printDate = () => {
  const d = new Date();
  const year = d.getFullYear();
  const month = d.getMonth() > 8 ? d.getMonth() + 1 : "0" + (d.getMonth() + 1);
  const date = d.getDate() > 9 ? d.getDate() : "0" + d.getDate();
  const hours = d.getHours() > 9 ? d.getHours() : "0" + d.getHours();
  const minutes = d.getMinutes() > 9 ? d.getMinutes() : "0" + d.getMinutes();
  const seconds = d.getSeconds() > 9 ? d.getSeconds() : "0" + d.getSeconds();
  return `${year}-${month}-${date}`;
}

const copy = () => {
  var clipboard = new Clipboard('.tag-read')
  clipboard.on('success', e => {
    // console.log('复制成功')
    layer.msg("复制成功");
    // 释放内存
    clipboard.destroy()
  })
  clipboard.on('error', e => {
    // 不支持复制
    // console.log('该浏览器不支持自动复制')
    // 释放内存
    clipboard.destroy()
  })
}
const add = () => {  // 新增
  data.form = {
    "projectStartTime": printDate(),
    "illuminance": '',
    "originalIlluminance": '',
    "investmentAmount": "",
    "latitude": "''",
    "attributes": "",
    "id": '',
    projectName: "",
    electricityPrice: "",
    projectLightInfos: [{
      "amount": "",
      "lightName": "",
      "power": ""
    }]
  }
  users.value = [];
  mainIndex = layer.open({
    type: 1,
    title: locale.value == 'zh' ? '新增公司' : 'addItem',
    content: $("#saveOr3UpdateDiv"),
    area: ['800px', '380px'],
    offset: ['100px'],
    success: function (index) {
      //清空表单数据
      // $("#dataFrm")[0].reset();
      url = $httpUrl + "/role/insertRole";
    }
  });
}





// const getUnactiveDev = () => {
//   $axios.post('/device/getUnactiveDev', {}).then(res => {

//     // data.loading = false;
//     // data.tableData = res.data.data
//     //  data.total = res.data.data.total
//   })
// }


const generateData = () => {
  $axios.post('/device/getUnactiveDev', {}).then(res => {
    transferOld = res.data.data == null ? [] : res.data.data
    if (res.data.data == null) {
      res.data.data = [];
    }
    res.data.data.map((item) => {
      transferdata.value.push({
        key: item.id,
        label: item.nickName
      })
    })

  })
}
let oneDeviceArr = [];
const transferdata = ref([])
const transfervalue = ref([])
let oldValue = [];
let rowData = {};
let users = ref([]);
let oldUser = [];
const check = (oldUser) => {
  //userOptions.value
  let arr = userOptions.value.filter((item) => {
    return oldUser.userid == item.userid;
  })
  if (arr.length > 0) {
    return false;
  } else {
    return true;
  }
}
const uniqueFunc = (arr, uniId) => {
  const res = new Map();
  return arr.filter((item) => !res.has(item[uniId]) && res.set(item[uniId], 1));
}

const edit = (row) => { // 编辑
  // upload.value.clearFiles()

  fileList.value = [{
    name: 'logo.jpeg',
    url: 'data:image/jpg;base64,' + row.binData,
  }]
  data.form.originalIlluminance = row.domain;
  data.form.projectName = row.description;




  //   userOptions.value=[];
  // electricMetersList.value = oldElectricMetersList
  // userOptions.value = JSON.parse(JSON.stringify(oldUserList));
  // for (let i = 0; i < row.electricMeters.length; i++) {
  //   row.electricMeters[i].dsb = true;
  //   electricMetersList.value.push(row.electricMeters[i]);
  // }
  // transfervalue.value = [];
  // let arr = [];
  // transferdata.value = [];
  // rowData = row;
  // getUnactiveDev();
  // return;
  mainIndex = layer.open({
    type: 1,
    title: locale.value == 'zh' ? '修改' : 'update',
    content: $("#saveOr3UpdateDiv"),
    area: ['800px', '380px'],
    success: function (index) {
      // data.form = row;
      // if (data.form.projectLightInfos.length == 0) {
      //   data.form.projectLightInfos = [
      //     {
      //       "amount": "",
      //       "lightName": "",
      //       "power": ""
      //     }
      //   ]
      // }
      ///form.val("dataFrm", data);
      /// url = $httpUrl + "/role/updateRole";


      // axios.post($httpUrl + '/user/UsersByProjectId', {
      //   "deviceFid": row.id,
      // }).then(res => {
      //   oldUser = res.data.data;
      //   for (let i = 0; i < res.data.data.length; i++) {
      //     /// if (check(res.data.data[i])) {
      //     userOptions.value.push(res.data.data[i]);
      //     /// }
      //   }
      //   userOptions.value = uniqueFunc(userOptions.value, 'userid')
      //   users.value = res.data.data.map((item) => {
      //     return item.userid;
      //   })
      //   //  
      //   //  users.value=res.data.data;
      // })






      // axios.post($httpUrl + '/device/getChildDevice', {
      //   "deviceFid": row.id,
      // }).then(res => {
      //   oneDeviceArr = res.data.data;
      //   //// console.log(transferOld);
      //   for (let i = 0; i < res.data.data.length; i++) {
      //     // transferOld.push(data.data[i])
      //     let item = res.data.data[i]
      //     transferdata.value.push({
      //       key: item.id,
      //       label: item.nickName
      //     })
      //     // transfervalue.value.push(item.id)
      //   }

      //   for (let i = 0; i < transferOld.length; i++) {
      //     transferdata.value.push({
      //       key: transferOld[i].id,
      //       label: transferOld[i].nickName
      //     })
      //   }


      //   for (let i = 0; i < res.data.data.length; i++) {
      //     let item = res.data.data[i]
      //     arr.push(item.id);
      //   }
      //   transferdata.value = transferdata.value.filter(function (item, index, self) {
      //     return self.findIndex(el => el.key == item.key) === index
      //   })

      //   transferOld = transferOld.filter(function (item, index, self) {
      //     return self.findIndex(el => el.id == item.id) === index
      //   })

      //   let uniqueArray = arr.filter((item, index, array) => {
      //     return array.indexOf(item) === index
      //   })


      //   oldValue = arr;
      //   transfervalue.value = uniqueArray
      //  // console.log("transfervalue", transfervalue.value);


      //   ////  window.setTimeout(function () {
      //   // $(".clickb").dblclick(function (event) {
      //   //   ///alert($(this).parents(".el-transfer-panel__item").index())
      //   //   let index = $(this).parents(".el-transfer-panel__item").index() * 1;
      //   //   changeRight($(this).html(), index)
      //   //   event.stopPropagation();
      //   //   event.preventDefault();
      //   //   return false;
      //   // })
      //   // $(".el-checkbox__label span").on("dblclick", function () {
      //   //   changeRight($(this).html())
      //   // });



      //   // $("body").on("click", ".clickb", function (event) {
      //   //   $(".clickb").dblclick(function (event) {
      //   //     ///alert($(this).parents(".el-transfer-panel__item").index())
      //   //     let index = $(this).parents(".el-transfer-panel__item").index() * 1;
      //   //     changeRight($(this).html(), index)
      //   //     event.stopPropagation();
      //   //     event.preventDefault();
      //   //     return false;
      //   //   })
      //   // });











      //   /// }, 3500)

      // })

    }
  });
}
const onChanSize = (e) => {
  //修改分页数
  // 
  data.queryForm.page = 1;
  data.queryForm.limit = e;
  getList({});
}
const onChanPage = (e) => {
  //修改分页
  // 
  data.queryForm.page = e;
  getList({});
}

const del = (data) => { // 删除
  /// ElMessageBox.confirm('确认删除?', '提示').then(() => {
  // layer.confirm('真的删除【' + data.rolename + '】这个角色吗', function (index) {
  //   //向服务端发送删除指令
  //   $.post($httpUrl + "/role/deleteRole", { roleid: data.roleid }, function (res) {
  //     layer.msg(res.msg);
  //     //刷新数据 表格
  //     //  tableIns.reload();
  //     getList()
  //   })
  // });

  // ElMessageBox.confirm('确认删除 '+data.projectName+' 吗?', '提示').then(() => {
  //   axios.delete($httpUrl + '/ProjectInfo/delete', {
  //     data: data,
  //     headers: {
  //       'Content-Type': 'application/json'
  //     }
  //   }).then(res => {
  //     getList();

  //   })
  // })


  ElMessageBox({
    title: '提示',
    message: h('p', null, [
      h('span', null, '确认删除'),
      h('span', { style: 'color: red' }, ' ' + data.projectName + ' '),
      h('span', null, '吗?'),
    ]),
    showCancelButton: true,
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    beforeClose: (action, instance, done) => {
      if (action === 'confirm') {
        // instance.confirmButtonLoading = true
        // instance.confirmButtonText = 'Loading...'
        // setTimeout(() => {
        //   done()
        //   setTimeout(() => {
        //     instance.confirmButtonLoading = false
        //   }, 300)
        // }, 3000)


        axios.delete($httpUrl + '/ProjectInfo/delete', {
          data: data,
          headers: {
            'Content-Type': 'application/json'
          }
        }).then(res => {
          getList({});
          done()
        })
      } else {
        done()
      }
    },
  }).then((action) => {
    // ElMessage({
    //   type: 'info',
    //   message: `action: ${action}`,
    // })
  }).catch(() => { }) // 新增错误捕获























  // })
}
let activeName = ref("first");
let formRef = ref(null)

const submit = () => { // 提交新增/编辑表单
  formRef.value.validate(valid => {
    if (valid) {

    }
  })
}

const getList = (params) => { // 获取表格数据
  let projectName = '';
  if (params != undefined && params.projectName) {
    projectName = params.projectName;
  }
  data.loading = true;
  $axios.post('/ProjectInfo/getInfo', {
    deviceFid: '-1'
  }).then(res => {
    // console.log(23);
    data.loading = false;
    if (projectName) {
      let arr = res.data.data.filter(item => {
        return item.projectName && item.projectName.includes(projectName)
      })
      let newArr = arr.filter(item => {
        return item.id != null;
      })
      data.tableData = newArr;
    } else {
      let newArr = res.data.data.filter(item => {
        return item.id != null;
      })
      data.tableData = newArr;
    }

    //  data.total = res.data.data.total
  })
  // data.loading = false;
}
const doQuery = (params) => {
  getList(params);
}
const getWidth = () => {
  return (window.innerWidth - 417) + 'px';
}
const getHeight = () => {
  return (window.innerHeight - 116) + 'px';
}
const showType = (type) => {
  if (type == -1) return "系统";
  if (type == 0) return "云平台";
  if (type == 1) return "云产品";
  if (type == 2) return "云设备";
}

const selectRoleMenu = (data) => {
  openselectRoleMenu(data);
}


var tableIns;
var $ = '';
var layer = '';
var form = '';
var table = '';
var dtree = '';
var url = '';
var mainIndex = '';

var menuTree = '';
//打开分配菜单的弹出层
function openselectRoleMenu (data) {

  mainIndex = layer.open({
    type: 1,
    title: '分配【' + data.rolename + '】的角色',
    content: $("#selectRoleMenu"),
    area: ['400px', '450px'],
    btnAlign: 'c',
    btn: ['<div class="layui-icon layui-icon-release">确认分配</div>', '<div class="layui-icon layui-icon-close">取消分配</div>'],
    yes: function (index, layero) {
      var nodes = dtree.getCheckbarNodesParam("menuTree");
      var roleid = data.roleid;
      var params = "roleid=" + roleid;

      $.each(nodes, function (i, item) {
        params += "&ids=" + item.nodeId;
      })

      //保存角色和菜单的关系
      $.post($httpUrl + "/role/saveRoleMenu", params, function (res) {
        if (res.code = 200) {
          layer.msg(res.msg);
          //parent.layer.closeAll();
          //"#selectRoleMenu").hide();
          layer.close(mainIndex);
        } else {
          layer.msg(res.msg);
        }
      })
    },
    success: function (index) {
      //初始化树
      menuTree = dtree.render({
        elem: "#menuTree",
        dataStyle: "layuiStyle",  //使用layui风格的数据格式
        response: { message: "msg", statusCode: 0 },  //修改response中返回数据的定义
        dataFormat: "list",  //配置data的风格为list
        checkbar: true,//复选框
        checkbarType: "all", // 默认就是all
        checkbarData: "choose",
        url: $httpUrl + "/role/initRoleMenuTreeJson?roleid=" + data.roleid // 使用url加载（可与data加载同时存在）
      });
    }
  });
}

let images = ref(['https://www.baidu.com/img/PCtm_d9c8750bed0b3c7d089fa7d55720d6cf.png'])
let dialogVisible = ref();
let str1 = ref();
let str2 = ref();
let strId = ref();
let DeviceSecret = ref();
let textarea = ref(
  `{
    "TargetServerUri": "1973763779722255.iot-amqp.cn-shanghai.aliyuncs.com",
    "Port": "1883",
    "ProductKey": "h5n2naC5o6v",
    "DeviceName": "qlm00000099",
    "UserName": "h5n2naC5o6v,qlm00000099",
    "UserPassword": "A4C69F5CB7483D20E50A53FB09CB986BFEE69E2D",
    "DeviceSecret": "acff0be4ed62dfce9e440b27d429a14b"

  }`)

const changeRight = (key, index) => {

  let product_key = '';
  let device_name = '';
  let device_secret = '';

  // let arr = oneDeviceArr.filter((item) => {
  //   return item.nickName == key
  // })
  let arr = [oneDeviceArr[index]];
  product_key = arr[0].productKey;
  device_name = arr[0].deviceName;
  device_secret = arr[0].deviceSecret;
  strId.value = arr[0].id;
  DeviceSecret.value = arr[0].deviceSecret;



























  var chrsz = 8;  /* bits per input character. 8 - ASCII; 16 - Unicode      */
  /*
   * These are the functions you'll usually want to call
   * They take string arguments and return either hex or base-64 encoded strings
   */
  function hex_hmac_sha1 (key, data) { return binb2hex(core_hmac_sha1(key, data)); }

  /*
   * Calculate the SHA-1 of an array of big-endian words, and a bit length
   */
  function core_sha1 (x, len) {
    /* append padding */
    x[len >> 5] |= 0x80 << (24 - len % 32);
    x[((len + 64 >> 9) << 4) + 15] = len;

    var w = Array(80);
    var a = 1732584193;
    var b = -271733879;
    var c = -1732584194;
    var d = 271733878;
    var e = -1009589776;

    for (var i = 0; i < x.length; i += 16) {
      var olda = a;
      var oldb = b;
      var oldc = c;
      var oldd = d;
      var olde = e;

      for (var j = 0; j < 80; j++) {
        if (j < 16) w[j] = x[i + j];
        else w[j] = rol(w[j - 3] ^ w[j - 8] ^ w[j - 14] ^ w[j - 16], 1);
        var t = safe_add(safe_add(rol(a, 5), sha1_ft(j, b, c, d)),
          safe_add(safe_add(e, w[j]), sha1_kt(j)));
        e = d;
        d = c;
        c = rol(b, 30);
        b = a;
        a = t;
      }

      a = safe_add(a, olda);
      b = safe_add(b, oldb);
      c = safe_add(c, oldc);
      d = safe_add(d, oldd);
      e = safe_add(e, olde);
    }
    return Array(a, b, c, d, e);

  }

  /*
   * Perform the appropriate triplet combination function for the current
   * iteration
   */
  function sha1_ft (t, b, c, d) {
    if (t < 20) return (b & c) | ((~b) & d);
    if (t < 40) return b ^ c ^ d;
    if (t < 60) return (b & c) | (b & d) | (c & d);
    return b ^ c ^ d;
  }

  /*
   * Determine the appropriate additive constant for the current iteration
   */
  function sha1_kt (t) {
    return (t < 20) ? 1518500249 : (t < 40) ? 1859775393 :
      (t < 60) ? -1894007588 : -899497514;
  }

  /*
   * Calculate the HMAC-SHA1 of a key and some data
   */
  function core_hmac_sha1 (key, data) {
    var bkey = str2binb(key);
    if (bkey.length > 16) bkey = core_sha1(bkey, key.length * chrsz);

    var ipad = Array(16), opad = Array(16);
    for (var i = 0; i < 16; i++) {
      ipad[i] = bkey[i] ^ 0x36363636;
      opad[i] = bkey[i] ^ 0x5C5C5C5C;
    }

    var hash = core_sha1(ipad.concat(str2binb(data)), 512 + data.length * chrsz);
    return core_sha1(opad.concat(hash), 512 + 160);
  }

  /*
   * Add integers, wrapping at 2^32. This uses 16-bit operations internally
   * to work around bugs in some JS interpreters.
   */
  function safe_add (x, y) {
    var lsw = (x & 0xFFFF) + (y & 0xFFFF);
    var msw = (x >> 16) + (y >> 16) + (lsw >> 16);
    return (msw << 16) | (lsw & 0xFFFF);
  }

  /*
   * Bitwise rotate a 32-bit number to the left.
   */
  function rol (num, cnt) {
    return (num << cnt) | (num >>> (32 - cnt));
  }

  /*
   * Convert an 8-bit or 16-bit string to an array of big-endian words
   * In 8-bit function, characters >255 have their hi-byte silently ignored.
   */
  function str2binb (str) {
    var bin = Array();
    var mask = (1 << chrsz) - 1;
    for (var i = 0; i < str.length * chrsz; i += chrsz)
      bin[i >> 5] |= (str.charCodeAt(i / chrsz) & mask) << (32 - chrsz - i % 32);
    return bin;
  }

  /*
   * Convert an array of big-endian words to a hex string.
   */
  function binb2hex (binarray) {
    var hex_tab = "0123456789ABCDEF";
    var str = "";
    for (var i = 0; i < binarray.length * 4; i++) {
      str += hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8 + 4)) & 0xF) +
        hex_tab.charAt((binarray[i >> 2] >> ((3 - i % 4) * 8)) & 0xF);
    }
    return str;
  }


  function onSign () {
    var pk = document.getElementById("productKey").value;
    var dn = document.getElementById("deviceName").value;
    var ds = document.getElementById("deviceSecret").value;
    var ts = document.getElementById("timestamp").value;
    var ci = document.getElementById("clientId").value;
    var jcl = document.getElementById("jcl");

    var sm = document.getElementById("signMethod").value;
    var us = document.getElementById("username");
    var pw = document.getElementById("password");

    var ul = document.getElementById("url");
    var ar = document.getElementById("area").value;

    us.value = dn + '&' + pk;

    //jcl.value = 'ssss';
    jcl.value = ci + '|securemode=3,signmethod=hmacsha1,timestamp=' + ts + '|';
    //alert((ci+'|securemode=3,signmethod=hmacsha1,timestamp='+ts+'|'));
    ul.value = pk + '.iot-as-mqtt.' + ar + '.aliyuncs.com:1883';
    if (pk == null || pk == "" || dn == null || dn == ""
      || ds == null || ds == "" || ci == null || ci == "") {
      alert("productKey,deviceName,deviceSecret,clientId can not be empty");
      return;
    }
    var options = {
      productKey: pk,
      deviceName: dn,
      timestamp: ts,
      clientId: ci
    }
    if (ts == null || ts == "") {
      options = {
        productKey: pk,
        deviceName: dn,
        clientId: ci
      }
    }
    var keys = Object.keys(options).sort();
    // 按字典序排序
    keys = keys.sort();
    var list = [];
    keys.forEach(function (key) {
      list.push(key + options[key]);
    });
    var contentStr = list.join('');
    var sign = "";
    if (sm == "hmacmd5") {
      sign = hex_hmac_md5(ds, contentStr);
    } else if (sm == "hmacsha1") {
      sign = hex_hmac_sha1(ds, contentStr);
      // console.log(ds);
      // console.log(contentStr);
    } else {
      alert("method is invalid");
    }
    pw.value = sign.toUpperCase();
  }


  function test (options, ds) {
    var keys = Object.keys(options).sort();
    // 按字典序排序
    keys = keys.sort();
    var list = [];
    keys.forEach(function (key) {
      list.push(key + options[key]);
    });
    var contentStr = list.join('');
    var sign = "";
    sign = hex_hmac_sha1(ds, contentStr);
    return sign
  }
  function test2 (product_key, device_name, device_secret) {
    let options = {
      "productKey": product_key,
      "deviceName": device_name,
      "clientId": "12345"
    }
    return "AT+MQTT_PWD=" + test(options, device_secret);

  }
  // options = {
  //   "productKey": product_key,
  //   "deviceName": device_name,
  //   "clientId": "12345"
  // }
  str1.value = test2(product_key, device_name, device_secret);
  str2.value = "AT+MQTT_KEYNAME=" + product_key + "," + device_name;
  dialogVisible.value = true;




  let pwd = test2(product_key, device_name, device_secret).replaceAll('AT+MQTT_PWD=', '');
  let textareaObj = {
    "TargetServerUri": "1973763779722255.iot-amqp.cn-shanghai.aliyuncs.com",
    "Port": "1883",
    "ProductKey": product_key,
    "DeviceName": device_name,
    "UserName": product_key + ',' + device_name,
    "UserPassword": pwd,
    "DeviceSecret": arr[0].deviceSecret
  }
  textarea.value = JSON.stringify(textareaObj);
  textarea.value = JSON.stringify(JSON.parse(textarea.value), null, '\t')

}
let transferOld = [];
const changeTransfer = (str, st) => {
  if (st == 'right') {
    showRight(str, st)
  } else {
    showLeft(str, st);
  }
}
let upload = ref(null);
let domain = ref('');
const submitUpload = () => {
  if (data.form.projectName == '') {
    layer.msg("公司名称不能为空");
    return false;
  }

  if (data.form.originalIlluminance == '') {
    layer.msg("公司网址不能为空");
    return false;
  }
  dataup.value = { domain: data.form.projectName, description: data.form.originalIlluminance };

  if (uploadFiles.value.length === 0) {
    let formData = new FormData()
    formData.append("domain", data.form.projectName)
    formData.append("description", data.form.originalIlluminance)
    axios({
      method: "post",
      url: $httpUrl2 + '/img/upload',
      data: formData,
      headers: {
        "Content-Type": "multipart/form-data"
      }
    })
      .then((res) => {
      })
      .catch((err) => {
        console.error(err)
      })
  } else {
    upload.value.submit()
  }

  layer.msg("保存成功");

}


const showLeft = (str, st) => {
  // console.log(oldValue);
  let obj = [];
  if (str.length == 0) {
    obj = oldValue;
  } else {
    obj = oldValue.filter(el => !str.includes(el))
  }
  let list = [];
  for (let i = 0; i < obj.length; i++) {
    let arr = oneDeviceArr.filter((item) => {
      return item.id == obj[i]
    })
    list.push(arr[0]);
  }
  for (let i = 0; i < list.length; i++) {
    if (list[i]) {
      list[i].fid = 135;
      list[i].deviceStatus = 'UNACTIVE';
      ///list[i].nickName = '';
    }
  }
  // console.log("参数", list);

  for (let i = 0; i < list.length; i++) {
    $axios.post('/device/updateDevice', list[i]).then(res => {
      layer.msg("操作成功");
      if (i == list.length - 1) {
        axios.post($httpUrl + '/device/getChildDevice', {
          "deviceFid": rowData.id,
        }).then(res => {
          oneDeviceArr = res.data.data;
        })
      }
      /// edit(rowData);
      // data.loading = false;
      // data.tableData = res.data.data
      //  data.total = res.data.data.total
    })
  }



}
const showRight = () => {
  // console.log(oldValue);
  // console.log(transfervalue.value);
  let obj = [];
  for (let i = 0; i < transfervalue.value.length; i++) {
    let arr = transferOld.filter((item) => {
      return item.id == transfervalue.value[i]
    })
    obj.push(arr[0]);
  }
  for (let i = 0; i < obj.length; i++) {
    if (obj[i]) {
      obj[i].fid = rowData.id;
      obj[i].deviceStatus = 'OFFLINE';
    }

  }
  // console.log("参数", obj);
  for (let i = 0; i < obj.length; i++) {
    if (obj[i]) {
      $axios.post('/device/updateDevice', obj[i]).then(res => {
        layer.msg("操作成功");
        if (i == obj.length - 1) {
          axios.post($httpUrl + '/device/getChildDevice', {
            "deviceFid": rowData.id,
          }).then(res => {
            oneDeviceArr = res.data.data;
          })
        }
        // data.loading = false;
        // data.tableData = res.data.data
        //  data.total = res.data.data.total
      })
    }

  }
}



const syntaxHighlight = (json) => {
  if (typeof json != 'string') {
    json = JSON.stringify(json, undefined, 2);
  }
  json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
  return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
    var cls = 'number';
    if (/^"/.test(match)) {
      if (/:$/.test(match)) {
        cls = 'key';
      } else {
        cls = 'string';
      }
    } else if (/true|false/.test(match)) {
      cls = 'boolean';
    } else if (/null/.test(match)) {
      cls = 'null';
    }
    return '<span class="' + cls + '">' + match + '</span>';
  });
}


const addPower = () => {
  data.form.projectLightInfos.push({ amount: "", power: "", lightName: "" })
}
const subtractionbtnPower = (i) => {
  if (i == 0 && data.form.projectLightInfos.length == 1) {
    return false;
  }
  data.form.projectLightInfos.splice(i, 1);
}
let dialogVisible3 = ref(false);
let pwd = ref('');
const checkTime = () => {
  dialogVisible3.value = true;
}
let pwdFlag = ref(false);
let projectStartTime = ref();
const enterPwd = () => {
  if (pwd.value == '') {
    ElMessage({
      type: 'error',
      message: '请输入密码',
    })
    return;
  }
  let params = {
    pwd: pwd.value
  }
  axios.post($httpUrl + '/sel/authorization', params).then(res => {
    if (res.data.data) {
      ElMessage({
        type: 'success',
        message: `密码正确可以修改`,
      })
      dialogVisible3.value = false;
      pwd.value = '';
      pwdFlag.value = true;
      projectStartTime.value.focus();
    } else {
      ElMessage({
        type: 'error',
        message: '密码错误不能修改',
      })
    }
  })
}

let imei = ref();
let oldElectricMetersList = [];
let electricMetersList = ref([]);


// const login=()=>{

//   // let obj = new FormData();
//   // obj.append('username', 'admin');
//   // obj.append('password', 'admin');
//   // obj.append('rememberMe', true);

//   // $axios.post('/sel/login', obj).then(res => {

//   // }).catch(err => {

//   // })
// let obj={
//   username:"admin",
//   password:"admin"
// }


//   axios.post($httpUrl2+"/login", obj, function (res) {


//   })




// }

const login = () => {
  let obj = new FormData();
  obj.append('loginname', "admin");
  obj.append('pwd', "admin");

  axios.post($httpUrl2 + '/login', obj).then(res => {

  }).catch(err => {

    axios.post($httpUrl2 + err.config.url, obj).then(res => {

    }).catch(err => {


    })


  })


}

onMounted(() => {

  actionup.value = $httpUrl2 + '/img/upload';
  //actionup.value=actionup.value.replace('/api/api','/public');
  // console.log(actionup.value);
  // getElectricMetersList();
  // window.setTimeout(function () {
  //   $(".el-transfer-panel__item .el-checkbox__label span").dblclick(function (event) {
  //     changeRight($(this).html())
  //     event.stopPropagation();
  //   })
  //   // $(".el-checkbox__label span").on("dblclick", function () {
  //   //   changeRight($(this).html())
  //   // });
  // }, 3000)
  generateData();
  getuserList();
  layui.extend({
    dtree: '/layui_ext/dist/dtree'
  }).use(['jquery', 'layer', 'form', 'table', 'dtree'], function () {
    $ = layui.jquery;
    layer = layui.layer;
    form = layui.form;
    table = layui.table;
    dtree = layui.dtree;
    //保存
    form.on("submit(doSubmit)", function (obj) {
      if (data.form.projectName == '') {
        layer.msg("项目名称不能为空");
        return false;
      }
      if (data.form.projectStartTime == '') {
        layer.msg("请选择项目启动日期");
        return false;
      }
      // if(data.form.originalIlluminance==''){
      //   layer.msg("改造前地面照度");
      //   return false;
      // }
      // if(data.form.illuminance==''){
      //   layer.msg("改造后地面照度");
      //   return false;
      // }
      if (data.form.investmentAmount == '') {
        layer.msg("项目总投资不能为空");
        return false;
      }
      if (data.form.attributes == '') {
        layer.msg("客户属性不能为空");
        return false;
      }
      if (data.form.electricityPrice == '') {
        layer.msg("电价不能为空");
        return false;
      }
      if (users.value.length == 0 && data.form.id) {
        layer.msg("请选择所属所属用户");
        return false;
      }
      for (let i = 0; i < data.form.projectLightInfos.length; i++) {
        if (data.form.projectLightInfos[i].power == '') {
          layer.msg("改造前单灯功率不能为空");
          return false;
        }
        if (data.form.projectLightInfos[i].amount == '') {
          layer.msg("改造前单类数量不能为空");
          return false;
        }
      }
      //序列化表单数据
      var params = JSON.parse(JSON.stringify(data.form));
      if (params.id == '') {
        params.projectStartTime = params.projectStartTime + ' 00:00:00'
      }
      if (params.projectStartTime.length < 12) {
        params.projectStartTime = params.projectStartTime + ' 00:00:00'
      }
      if (!params.id) {
        delete params.id;
      }





      axios.put($httpUrl + '/ProjectInfo/saveOrUpdate', params).then(res => {
        layer.close(mainIndex);
        layer.msg("保存成功");
        getList({})
      })

      // let users=ref([]);
      // let oldUser=[];

      let arrUser = [];
      let arrDeviceInfoList = [];

      for (let j = 0; j < users.value.length; j++) {
        for (let i = 0; i < userOptions.value.length; i++) {
          if (userOptions.value[i].userid == users.value[j]) {
            arrUser.push(userOptions.value[i]);
            break;
          }
        }
      }
      let params2 = {
        "deviceFid": data.form.id,
        users: arrUser,
        deviceInfoList: oneDeviceArr
      }
      //// console.log(transferdata.value)
      // return;
      // 
      axios.put($httpUrl + '/UserDevices', params2).then(res => {
        /// layer.close(mainIndex);
        layer.msg("保存成功");
        // getList()
      })











    });

  })
})
</script>

<style lang="scss" scoped>
.layui-input-block {
  margin-left: 140px;
}

.layui-form-label {
  width: 110px;
}

.available1 {
  color: orangered;
}

#menuToolBar {
  display: flex;
  justify-content: left;
  align-items: left;
  flex: 1;
  padding-left: 20px;
}

:deep(.el-input__wrapper) {
  background: none;
  color: #fff;
}

:deep(.el-input__wrapper input) {
  background: none;
  color: #fff;
}

:deep(#dataFrm .el-input__inner) {
  color: #fff;
}

:deep(.el-transfer-panel) {
  background: none;
}

:deep(.el-transfer-panel .el-transfer-panel__header) {
  background: none;
  color: #fff;
}

:deep(.el-transfer-panel .el-transfer-panel__header .el-checkbox .el-checkbox__label) {
  color: #fff;
}

:deep(.el-transfer) {
  display: flex;
  flex-direction: row-reverse;
  align-items: center;
  justify-content: left;
}

:deep(.upload-demo .el-upload__tip) {
  color: #fff;
  font-size: 16px;
}

:deep(.el-transfer__buttons) {
  display: flex;
  flex-direction: row-reverse;
  align-items: center;
}

:deep(.el-transfer__button) {
  margin: 0 10px;
  transform: rotate(-180deg);
}

:deep(.el-transfer-panel__item.el-checkbox .el-checkbox__label span) {
  color: #fff;
  position: relative;
}

.tipsT {
  padding: 8px 6px;
  border: solid 1px #ddd;
  margin-bottom: 10px;
  font-size: 14px;
}

.tag-read {
  color: var(--el-color-primary);
  float: right;
}

.tipsBox {
  padding: 3px;
}

:deep(.el-table--enable-row-hover .el-table__body tr:hover>td.el-table__cell) {
  background: rgba(33, 112, 147, 0.3);
}

.lab {
  color: #fff;
  padding: 0 12px;
  display: inline-block;
}

.ruleFormlist {
  margin-bottom: 10px;
}

.timeBtn {
  display: block;
  width: 100%;
  opacity: 0;
  position: relative;
  height: 33px;
  z-index: 99;
}

.timeBtnBox {
  position: relative;
}

:deep(.timeDate) {
  position: absolute;
  top: 0;
}
</style>
<style>
.layui-layer-shade {
  z-index: 11 !important;
}

.layui-layer-page {
  z-index: 1111 !important;
}

.clickb {
  display: inline-block;
  width: 149px;
  height: 18px;
  position: absolute;
  left: -2px;
  top: 0px;

}

pre {
  outline: 1px solid #ccc;
  padding: 5px;
  margin: 5px;
}

.string {
  color: green;
}

.number {
  color: darkorange;
}

.boolean {
  color: blue;
}

.null {
  color: magenta;
}

.key {
  color: red;
}

#saveOr3UpdateDiv .layui-form-item {
  width: 100%;
  clear: none;
  margin-bottom: 12px;
}

.box {
  padding: 20px;
  width: 300px;
}

.rows {
  padding: 5px 0;
}
</style>